package com.lifeng.filter;

import com.alibaba.fastjson.JSON;
import com.lifeng.constant.ResCodeConstant;
import com.lifeng.service.TokenService;
import com.lifeng.utils.HttpResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:lifeng
 * @date:2020/4/9 14:16
 * 登录检查过滤器
 */
@Component
@Slf4j
public class LoginCheckFilter extends OncePerRequestFilter {
    @Resource
    private TokenService tokenService;
    private String[] whiteList = {"favicon.ico","login"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //Arrays.asList(whiteList).contains(request.getRequestURI());
        if(!request.getRequestURI().contains("login")
            && !request.getRequestURI().contains("favicon.ico")){//需要登录认证 就可以访问
            Map<String,Object> resData = new HashMap<>();
            String token = request.getHeader("token");
            if(StringUtils.isEmpty(token)){
                log.error("token为空");
                resData.put("code", ResCodeConstant.C1002);
                resData.put("msg","token为空");
                String json = JSON.toJSONString(resData);
                HttpResponseUtil.writeClient(response,json);
            }else{
                Boolean checkToken = tokenService.verifyToken(token);
                if(checkToken){
                    filterChain.doFilter(request,response);
                }else{
                    log.error("token无效");
                    resData.put("code",ResCodeConstant.C1003);
                    resData.put("msg","token无效");
                    String json = JSON.toJSONString(resData);
                    HttpResponseUtil.writeClient(response,json);
                }
            }
        }else{
            filterChain.doFilter(request,response);
        }
    }
}
